package net.xiaochengxu.dining.common.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
*FileName: BaseController.java
*@author lzd
*@version V1.0
*@Date: 2016年11月11日 下午2:37:32
*Description:基类控制器
*History:
*/
public class BaseController {

	public static Gson gson = (new GsonBuilder()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	public BaseController() {
	}

	public void initBinderPage(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("page.");
	}

	public static String getViewPath(String path) {
		if (path != null && !path.trim().equals(""))
			return (new StringBuilder()).append(path).toString();
		else
			return "";
	}

	public Map setJson(boolean success, String message, Object entity) {
		Map json = new HashMap();
		json.put("success", Boolean.valueOf(success));
		json.put("message", message);
		json.put("entity", entity);
		return json;
	}

	public String setExceptionRequest(HttpServletRequest request, Exception e) {
		logger.error(request.getContextPath(), e);
		StackTraceElement messages[] = e.getStackTrace();
		if (messages != null && messages.length > 0) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(e.toString()).append("<br/>");
			for (int i = 0; i < messages.length; i++)
				buffer.append(messages[i].toString()).append("<br/>");

			request.setAttribute("myexception", buffer.toString());
		}
		return "/common/error";
	}

	public Map setAjaxException(Map map) {
		map.put("success", Boolean.valueOf(false));
		map.put("message", "异步调用失败！");
		map.put("entity", null);
		return map;
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
	}

}
